package com.org.task;

import com.org.fileUpload.RemoveFile;
import com.org.properties.RedisKeyPropertis;
import com.org.service.BackupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;

@Component
@Slf4j
public class TaskHandler {

    @Autowired
    private BackupService backupService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RemoveFile removeFile;

    /**
     * 每天0点执行
     * 删除30天前的备份数据
     */
    @Scheduled(cron = "0 0 0 1/1 * ? ")
    public void everyDayTask(){
        //1.删除30天前的失物招领和寻物启事的备份数据
        log.info("开始删除30天前的备份数据");
        LocalDateTime time = LocalDateTime.now().minusDays(30);
        backupService.deleteAll(time);
    }

    /**
     * 每天0点执行一次
     * 删除上传的垃圾文件
     */
    @Scheduled(cron = "0 0 0 1/1 * ? ")
    public void removeRubbishFile(){
        //1、获取Redis中的所有文件集合
        Set<String> allFilePath = stringRedisTemplate.opsForSet().members(RedisKeyPropertis.REDIS_KEY_UP_ALL);
        //2、获取Redis中的垃圾文件集合
        Set<String> useFilePath = stringRedisTemplate.opsForSet().members(RedisKeyPropertis.REDIS_KEY_UP_USE);
        //3.比较集合，获取未相交的文件集合
        List<String> removeFilePath = allFilePath.stream().filter(filePath -> !useFilePath.contains(filePath)).toList();
        log.info("需要删除的垃圾文件有：{}", removeFilePath);
        //3.2、判断是否存在垃圾文件
        if(removeFilePath.isEmpty()){
            return;
        }
        //4.删除垃圾文件
        try {
            removeFile.deleteFile(removeFilePath);
        } catch (Exception e) {
            log.error("删除垃圾文件失败,异常信息：{}", e.getMessage());
            return;
        }
        //5.批量删除Redis中的垃圾文件集合
        stringRedisTemplate.opsForSet().remove(RedisKeyPropertis.REDIS_KEY_UP_ALL, removeFilePath.toArray());
    }

}
